<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

require_once APPPATH . 'controllers/admin.php';

/**
 * Контроллер просмотра и редактирования торрентов видео
 *
 * @package CoreFramework
 * @version 1.0
 * @author Gennadiy Kozlenko
 */
class Admin_Manage_Torrents extends Admin {
     
    /**
     * Идентификатор видео
     * @var int
     */
    private $idVideo = 0;
     
    /**
     * Конструктор класса
     *
     * @access public
     * @return Admin_Manage_Torrents
     */
    function Admin_Manage_Torrents() {
        parent::Admin();
        $this->set_menu(6, 5);
        $this->load->language('button');
        $this->load->language('video');
        if (false !== $this->input->get('video')) {
            $this->idVideo = (int) $this->input->get('video');
        }
        $this->load->model('m_video');
        $this->m_video->set_id($this->idVideo);
        if (0 == $this->m_video->get_id('id_video')) {
            $this->redirect('admin_manage_videos');
        }
        $this->add_param('id_video', $this->idVideo);
        $this->add_param('video_title', $this->m_video->get('title'));
    } // end Admin_Manage_Torrents
     
    /**
     * Метод по умолчанию
     *
     * @access public
     */
    function index() {
        $data = array();
        $this->load->helper('link');
        $this->load->model('m_select_torrents');
        $this->m_select_torrents->setVideo($this->idVideo);
        $this->m_select_torrents->initialize();
        $this->m_select_torrents->add_sort('id', false);
        $this->load->library('table_builder');
        $this->table_builder->set_model($this->m_select_torrents);
        $this->table_builder->add_button(create_link($this->get_controller(), 'add', array('video' => $this->idVideo)), $this->lang->line('add_button'));
        $this->table_builder->add_button(create_link($this->get_controller(), 'edit', array('video' => $this->idVideo)), $this->lang->line('edit_button'));
        $this->table_builder->add_button(create_link($this->get_controller(), 'delete', array('video' => $this->idVideo)), $this->lang->line('delete_button'), $this->lang->line('torrents_delete_confirmation'));
        $data['table'] = $this->table_builder->generate();
        $this->set_content($this->parser->parse('admin/manage_torrents.html', $data, true));
        $this->display();
    } // end index
     
    /**
     * Метод удаления записей
     *
     * @access public
     */
    function delete() {
        $ids = $this->input->post('ids');
        $count = 0;
        if (is_array($ids) && 0 < count($ids)) {
            $this->load->model('m_video_torrent');
            foreach ($ids as $id) {
                $this->m_video_torrent->set_id($id);
                if ($this->m_video_torrent->delete()) {
                    $count++;
                }
            }
            if (0 == $count) {
                $this->set_message($this->lang->line('delete_torrents_error'), 'error', true);
            } elseif ($count != count($ids)) {
                $this->set_message($this->lang->line('delete_torrents_warn'), 'help', true);
            } else {
                $this->set_message($this->lang->line('delete_torrents_succ'), 'info', true);
            }
        }
        $this->redirect($this->get_controller(), 'index', array('video' => $this->idVideo));
    } // end delete
     
    /**
     * Метод добавления записи
     * Редирект на нужный контроллер
     *
     * @access public
     */
    function add() {
        $this->redirect('admin_update_torrent', 'index', array('video' => $this->idVideo));
    } // end add
     
    /**
     * Метод изменения записи
     * Редирект на нужный контроллер
     *
     * @access public
     */
    function edit() {
        $ids = $this->input->post('ids');
        if (is_array($ids) && 0 < count($ids)) {
            $id = array_shift($ids);
            $this->redirect('admin_update_torrent', 'index', array('id' => $id, 'video' => $this->idVideo));
        }
        $this->redirect($this->get_controller());
    } // end edit

    /**
     * Upload torrent file
     */
    function upload() {
        $data = array();
        $torrent = '';
        $result = false;
        if (false !== $this->input->post('upload')) {
            $result = true;
            $config = array(
            	'upload_path'   => $this->config->item('upload_path'),
            	'allowed_types' => 'torrent',
            	'max_size'      => 1024,
            	'encrypt_name'  => true
            );
            $this->load->library('upload', $config);
            if ($this->upload->do_upload('torrent')) {
                $torrent_data = $this->upload->data();
                // Перемещаем torrent в нужную папку
                $path = 'data/torrents/' . substr($torrent_data['file_name'], 0, 2) . '/';
                $full_path = BASEPATH . '../' . $path;
                if (!file_exists($full_path)) {
                    mkdir($full_path, 0777, true);
                }
                if (copy($torrent_data['full_path'], $full_path . $torrent_data['file_name'])) {
                    // Все удачно прошло
                    $torrent = $path . $torrent_data['file_name'];
                } else {
                    // Неудалось закачать файл
                    $this->errors->set('torrent', $this->lang->line('upload_destination_error'));
                    $result = false;
                }
                // Удаляем файл из временной папки
                @unlink($torrent_data['full_path']);
            } else {
                $torrent = '';
                $this->errors->set('torrent', $this->upload->display_errors('', ''));
                $result = false;
            }
        }
        // Забиваем в дату поля
        $data['torrent'] = $torrent;
        $data['succ'] = $result ? array(array()) : array();
        $this->set_content($this->parser->parse('admin/upload_torrent.html', $data, true));
        $this->set_layout('iframe');
        $this->display();
    }
     
}
